package com.book.service.impl;

import com.book.mapper.BookMapper;
import com.book.pojo.Book;
import com.book.service.BookService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * @author xuchangshuo
 * @date 2020/10/29 15:17
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List findAllBook() {
        List<Book> books = bookMapper.selectAll();
        return books;
    }

    @Override
    public boolean addBook(Book book) {
        int i = bookMapper.insertSelective(book);
        if (i != 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean editBook(Book book) {
        int i = bookMapper.updateByPrimaryKeySelective(book);
        if (i != 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(int id) {
        int i = bookMapper.deleteByPrimaryKey(id);
        if (i != 0) {
            return true;
        }
        return false;
    }

    @Override
    public Page<Book> findPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);

        List<Book> books = bookMapper.selectAll();

        PageInfo<Book> info = new PageInfo<>(books);
        Page<Book> list = (Page<Book>) info.getList();

        return list;
    }

    @Override
    public List search(Map<String, String> map) {
        //封装查询条件
        Example example = new Example(Book.class);

        Example.Criteria criteria = example.createCriteria();

        if (map != null) {
            if (map.get("name") != null || "".equals(map.get("name"))) {
                criteria.andEqualTo("name", map.get("name"));
            }
        }
        List<Book> books = bookMapper.selectByExample(example);
        return books;
    }


    //获取缓存中的数据
    @Override
    public void getRedisData(){
        ValueOperations value = redisTemplate.opsForValue();
        HashOperations ops = redisTemplate.opsForHash();
        RedisOperations operations = ops.getOperations();
        BoundGeoOperations setmealPicDbResources = operations.boundGeoOps("setmealPicDbResources");
        Object key = setmealPicDbResources.getKey();
        System.out.println(key);
        System.out.println(setmealPicDbResources);
        String picDbResources = (String) value.get("setmealPicDbResources");
        System.out.println(picDbResources);
    }


}
